package com.tbit.uqbike.service.rpcservice;

import com.tbit.uqbike.constant.OperaPswConstant;
import com.tbit.uqbike.enums.SystemCodeEnum;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.Machine;
import com.tbit.uqbike.object.pojo.MachineBorrow;
import com.tbit.uqbike.object.pojo.User;
import com.tbit.uqbike.service.base.MachineService;
import com.tbit.uqbike.service.business.UserService;
import com.tbit.uqbike.webmanager.dao.core.MachineBorrowDao;
import com.tbit.utils.NullUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Author HZW
 * @ClassName BaseAwardTemplate
 * @Description
 * @date 2022/5/9 9:16
 * @Version 1.0
 */
@Slf4j
public abstract class BaseAwardTemplate {

    protected User user;
    protected MachineBorrow machineBorrow;
    @Autowired
    private MachineService machineService;
    @Autowired
    private MachineBorrowDao machineBorrowDao;
    @Autowired
    private UserService userService;
    private Machine machine;

    /**
     * 合同模板
     *
     * @return {@link Boolean}
     */
    public Boolean awardTemplate(String userCode, Integer money, String remark, String secret) {
        this.dataVerification(secret);
        this.initData(userCode);
        return this.cutPayment(user, machineBorrow, machine, money, remark);
    }

    private void initData(String userCode) {
        /**车辆校验*/
        machine = machineService.getByUserCode(userCode);
        /**借车记录校验*/
        machineBorrow = machineBorrowDao.getByMachineId(machine.getMachineId());
        /**用户信息查询*/
        user = userService.getByUserId(machineBorrow.getUserId());
    }

    /**
     * 数据验证
     *
     * @param secret 秘密
     */
    protected void dataVerification(String secret) {
        /**秘钥校验*/
        if (!OperaPswConstant.ORDER_FINISH_MANUAL.equals(secret)) {
            throw new BaseException(SystemCodeEnum.SECRET_ERROR);
        }
        if (machine == null) {
            throw new BaseException(SystemCodeEnum.MACHINE_NOT_EXIST);
        }
        if (machineBorrow == null) {
            throw new BaseException(SystemCodeEnum.MACHINE_BORROW_NOT_EXIST);
        }
        /**用户信息校验*/
        if (user == null) {
            throw new BaseException(SystemCodeEnum.USER_NOT_EXIST);
        }
        /**给用户的欠款字段赋值*/
        if (NullUtils.isEmpty(user.getRideMoney())) {
            user.setRideMoney(0);
        }

    }


    /**
     * 扣款
     *
     * @param user          用户
     * @param machineBorrow 借车对象
     * @param machine       车辆
     * @param money         钱
     * @param remark        备注
     * @return {@link Boolean}
     */
    protected abstract Boolean cutPayment(User user, MachineBorrow machineBorrow, Machine machine, Integer money, String remark);
}
